#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <set>
using namespace std;
class Solution
{
public:
    int atMostK(vector<int> &A, int K)
    {
        int res = 0, left = 0, right = 0, cnt = 0;
        vector<int> freq(A.size() + 1, 0);
        while (right < A.size())
        {
            if (freq[A[right]] == 0)
                cnt++;
            freq[A[right++]]++;
            while (cnt > K)
            {
                freq[A[left]]--;
                if (freq[A[left++]] == 0)
                    cnt--;
            }
            res += right - left;
        }
        return res;
    }
    int subarraysWithKDistinct(vector<int> &A, int K)
    {
        return atMostK(A, K) - atMostK(A, K - 1);
    }
};